<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="keyword"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="inputFn"
      @search="onSearch(keyword)"
    >
      <template #action>
        <div @click="onSearch(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="keyword">
      <van-cell
        @click="onSearch(item)"
        v-for="(item, index) in sugList"
        :key="index"
        icon="search"
      >
        <span v-html="highLight(item, keyword)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        @click="onSearch(item)"
        v-for="item in history"
        :key="item"
        :title="item"
      >
        <van-icon name="close" @click.stop="delFn(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import {
  setStorageSearchHistory,
  getStorageSearchHistory
} from '@/utils/storage'
import { gteSuggest } from '@/api/search'
export default {
  name: 'Search',
  data() {
    return {
      keyword: '',
      sugList: [],
      history: getStorageSearchHistory()
    }
  },
  methods: {
    // 参数2：高亮的关键字
    highLight(str, keyword) {
      const reg = new RegExp(this.keyword, 'gi')
      return str.replace(reg, (match) => {
        return `<span style="color: red;">${match}</span>`
      })
    },
    // 输入关键字发送请求
    inputFn() {
      // 防抖优化
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (this.keyword.length === 0) {
          // 如果内容为空则不执行后面的
          return
        }
        const res = await gteSuggest(this.keyword)
        // console.log(res)
        // console.log(res.data.options)
        // 处理没有数据的情况,避免报错
        if (res.data.options[0] === null) {
          // 这次是没有数据的
          return (this.sugList = [])
        }
        this.sugList = res.data.options
      }, 300)
    },
    onSearch(item) {
      console.log(item)
      // 先删
      this.history = this.history.filter((v) => v !== item)
      // 在添加
      this.history.unshift(item)
      setStorageSearchHistory(this.history)

      // 跳转页面
      this.$router.push({
        path: '/search/result',
        query: {
          word: item
        }
      })
    },
    // 删除历史记录
    delFn(item) {
      this.history = this.history.filter((v) => v !== item)
      setStorageSearchHistory(this.history)
    }
  }
}
</script>

<style></style>
